<?php
namespace app\index\controller;
use app\model\User as UserModel;
use think\Db;

use think\captcha\Captcha;
use app\lib\aliyun\Api as aliyunApi;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class User extends Base
{
    public $exception = ['login','getcaptcha','getloginsms','mlogin','forget','productcontact','accountcheck','register','token360','tokenCheck360'];

    public function __construct(){
        $model = new UserModel();
        $this->model = $model;
        parent::__construct();

        $page_info = $this->page_info;
        $page_info['title'] = '用户';

        $this->assign([
            'model'=>$model,
            'page_info'=>$page_info,
        ]);
    }

    public function token360(){


        return view('token360');
    }

    public function tokenCheck360(){
        if (request()->isPost()) {
            // 需要先将公钥pkcs1转成pkcs8
            // openssl目录：C:\Program Files\OpenSSL-Win64
            // openssl rsa -RSAPublicKey_in -in C:/dev.pem -pubout -out C:/public.pkcs8.pem
            $publicKey = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx2vKktjV8DvUm5MPYa+d
I3lobAdPXRUPt+ZmKYcserGTb0h8pPe6zX1RYxhd96g47/MHD7VSmFBIayjnlK/m
Izxl4KQx+rLEVqS5LejPtIwLvrh0zRj05MqxqDwfAM1YkMvYpbnifeDdQ22uK4TE
PoKI80z7HW0i7Js0WiPctez79XBj8heRYPtdrkGIGacluubAmnFDQQiHOD8gCKZo
FzFbFbJmWR5cb679e2U7dHOWQsdpX0zl+nkjtf9ED2fwiDGt6uVK9Z7MLmAvKUuS
2XDaCXdnYB0QqrB8e4LrHiBn+SpezksISXE0ToI1Z1K9jP1cQ/3vYjZo87C6fLgu
NwIDAQAB
-----END PUBLIC KEY-----';

            // $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOjEwMDAwNCwidXNlcm5hbWUiOiJkZXl1biIsImlzX3N1cGVydXNlciI6ZmFsc2UsImV4cCI6MTcwNTkwMjM2OSwiY3VyIjoxNzA1OTAyMDY5LjgyODU1NTN9.C9Z9e3hz58jt979RSOc8y11dHPe28IqcCdm7_XSLRZhdJIP9labpK03qOmd6vHFSrPYP9CniGf3ZyHurKcSmg46kNxQZK1mS_MJMajcKKdwLaLX1OQ-4103m5PwWAxw_kQxMv6dfo_IFI_iZeJ0nTyv-C80RU5L401ajjUU95Pp1wkqq95esnoOEVdIZTUvvzREuFvB64z9VRfFsexeDZDipuF92CstpluURyUHv0R36khW_iXIw_Y4wi2yh6wRiMvjKp2l7iltUKvUctWn1sQTcP5GvchapT9gGgSMvGUn3zD1AdW4TIq6vIwrcWt-RUbOgQd4OXQq4yZHBKAE7tA';
            $token = input('token');
            if (empty($token)) {
                return json(['code'=>5000,'msg'=>'请传入token']);
            }
            try {
                $decoded = JWT::decode($token, new Key($publicKey, 'RS256'));
                if (empty($decoded)) {
                    return json(['code'=>5000,'msg'=>'token无效']);
                }
                $decoded = json_decode(json_encode($decoded),true);
                if (empty($decoded['uid'])) {
                    return json(['code'=>5000,'msg'=>'token无效']);
                }
            } catch (\Exception $e) {
                return json(['code'=>5000,'msg'=>'token无效']);
            }
            
            $openuid = '360_'.$decoded['uid'];
            $map = [
                ['openuid','=',$openuid]
            ];
            $data = Db::name('user')->where($map)->find();
            if ( empty($data) ) {
                $save_data = [
                    'openuid'=>$openuid,
                    'ctime'=>time(),
                    'login_time'=>time(),
                    'nickname'=>$decoded['username'],
                    'source'=>2
                ];
                $save_data['headimgurl'] = Db::name('config')->where('key','USER_DEFAULT_IMG')->value('value');

                if ( Db::name('user')->insert($save_data) ) {
                    $data = Db::name('user')->where('openuid',$openuid)->find();
                }else{
                    return json(['code'=>5000,'msg'=>'注册失败']);
                }
            }else{
                Db::name('user')->where('id',$data['id'])->update(['login_time'=>time()]);
            }
            session('cch_user',$data);
            $x_access_token = base64_encode($openuid);
            return json(['code'=>2000,'x_access_token'=>$x_access_token]);
        }
    }

    public function read(){
        $ulogin = $this->login_user;
        $data = Db::name('user')->where('id',$ulogin['id'])->find();
        $data['ctime'] = date('Y-m-d H:i:s',$data['ctime']);
        return json(['code'=>2000,'data'=>$data]);
    }

    public function accountCheck($account){
        if ( !isMobile($account) ) {
            return json(['status'=>0]);
        }
        $model = new UserModel();
        $emails = $model->where([
            ['mobile','=',$account],
            ['is_delete','=',0]
        ])->column('email');
        if ( empty($emails) ) {
            return json(['status'=>-1,'msg'=>'当前账号不存在']);
        }elseif ( count($emails) == 1 ) {
            return json(['status'=>0]); 
        }else{
            return json(['status'=>1,'emails'=>$emails]);
        }
    }

    public function getLoginSms($mobile='',$is_check=0){
        if (strlen($mobile) != 11) {
            $this->error('手机号格式错误');    
        }
        $model = $this->model;
        if ($is_check == 1 && $model->where('mobile',$mobile)->count() > 0) {
            $this->error('手机号已被占用'); 
        }
        $code = rand(1000,9999);
        $sms_res = sendSms($mobile,'您的验证码是：'.$code,'得力云');
        // $code = 1234;
        // $sms_res['status'] = 1;
        if ($sms_res['status'] == 1) {
            session('sms_'.$mobile,$code);
            $this->success('发送成功');    
        }else{
            $this->error($sms_res['msg']);  
        }
    }

    // public function register(){
    //     $model = $this->model;
    //     if (request()->isPost()) {
    //         // $this->assign(['data'=>request()->param()]);
    //         $fields = [
    //             'must'=>['account_attr','mobile','email','password','license_type','license_number','license_images'],
    //             'nomust'=>['admin_id']
    //         ];
    //         if (input('account_attr') == 1) {
    //             $fields['must'][] = 'enterprise';
    //         }else{
    //             $fields['must'][] = 'last_name';
    //             $fields['must'][] = 'first_name';
    //         }
    //         $param = paramFilter(request()->param(),$fields);
    //         if (!empty($param['error_msg'])) {
    //             $this->error($param['error_msg']);
    //         }
    //         $admin_id = session('register_admin_id');
    //         if (!empty($admin_id)) {
    //             $param['admin_id'] = $admin_id;
    //         }

    //         $param['license_images'] = delArrEmpty($param['license_images']);
    //         if (empty($param['license_images'])) {
    //             $this->error('证件图片不能为空，如果选择了图片，记得点击开始上传按钮');    
    //         }
    //         if (!isMobile($param['mobile'])) {
    //             $this->error('手机号格式错误');    
    //         }
    //         $verify = input('verify');
    //         if (empty($verify) || $verify != session('sms_'.$param['mobile'])) {
    //             $this->error('验证码错误');       
    //         }
    //         if (strlen($param['password']) < 6) {
    //             $this->error('密码至少要有6位长度');  
    //         }

    //         if (strlen($param['email']) < 6) {
    //             $this->error('邮箱至少要有6位长度');  
    //         }elseif (strpos($param['email'], '@') !== false) {
    //             $this->error('邮箱不能含有@字符');  
    //         }

    //         $param['email'] = $param['email'].'@biaocloud.cn';
    //         if (!isEmail($param['email'])) {
    //             $this->error('邮箱：'.$param['email'].'格式错误'); 
    //         }elseif ($model->where('email',$param['email'])->count() > 0) {
    //             $this->error('邮箱：'.$param['email'].'已被占用'); 
    //         }
            
    //         $param['password'] = md5($param['password']);
    //         $param['license_images'] = implode(',', delArrEmpty($param['license_images']));
    //         // 判断是个人还是企业
    //         if ($param['account_attr'] == 1) {
    //             $param['name'] = $param['enterprise'];
    //         }else{
    //             $param['name'] = $param['last_name'].$param['first_name'];    
    //         }
    //         $param['source'] = 1;
    //         $param['ctime'] = $param['utime'] = time();

    //         // 如果域名是个性化的，则注册用户归属该域名的销售
    //         if ( empty($param['admin_id']) ) {
    //             $system_url = request()->host();
    //             $system_admin_id = Db::name('admin_config')->where('system_url',$system_url)->value('admin_id');
    //             if (!empty($system_admin_id)) {
    //                 $param['admin_id'] = $system_admin_id;
    //             }
    //         }

    //         Db::startTrans();
    //         try{
    //             $user_id = $model->insertGetId($param);
    //             if ( empty($user_id) ) {
    //                 throw new \Exception("用户添加失败");
    //             }
    //             if ( !Db::name('sms_rule')->insert([
    //                 'user_id'=>$user_id
    //             ]) ) {
    //                 throw new \Exception("消息规则添加失败");
    //             }
    //             Db::commit();
    //         } catch (\Exception $e) {
    //             Db::rollback();
    //             $this->error($e->getMessage());
    //         }
    //         // 发送短信通知
    //         if (!empty($param['admin_id'])) {
    //             $admin_mobile = Db::name('admin')->where('id',$param['admin_id'])->value('mobile');
    //         }
    //         if (empty($admin_mobile)) {
    //             $admin_mobile = '15915475458';
    //         }
    //         sendSms($admin_mobile,'新用户注册：'.$param['email'].'，请登录销售平台审核','得力云');
    //         $this->success("注册成功，请联系业务经理审核",url('user/login'));
    //     }
    //     if (input('?admin_id')) {
    //         session('register_admin_id',input('admin_id'));
    //     }

    //     return view('register', [
    //         'account_attr'=>$model->getAccountAttrList(),
    //         'license_type'=>$model->getLicenseTypeList()
    //     ]);
    // }

    public function forget(){
        if (request()->isPost()) {
            $model = $this->model;
            $param = request()->param();

            if (!isMobile($param['mobile'])) {
                $this->error('手机号格式错误');    
            }
            if (empty($param['verify']) || $param['verify'] != session('sms_'.$param['mobile'])) {
                $this->error('验证码错误');       
            }
            if (empty($param['password']) || strlen($param['password']) < 6) {
                $this->error('密码至少要有6位长度');  
            }

            $data = $model->where([
                ['mobile','=',$param['mobile']],
                ['is_delete','=',0]
            ])->find();
            if ( empty($data) ) {
                $this->error("账号不存在");
            }else{
                // 更新登录时间
                $model->where('id',$data['id'])->update(['password'=>md5($param['password'])]);
                session('sms_'.$param['mobile'],null);
                $this->success('修改成功',url('login'));
            }
        }
        return view('forget', [
            
        ]);
    }

    // public function login(){
    //     if (request()->isPost()) {
    //         $param = request()->param();
    //         $data = Db::name('user')->where('mobile',$param['mobile'])->find();
    //         if ( $data['password'] != md5($param['password']) ) {
    //             $this->error("账号或密码错误");
    //         }else{
    //             // 更新登录时间
    //             Db::name('user')->where('id',$data['id'])->update(['login_time'=>time()]);
    //             session('cch_user',$data);
    //             return redirect(url('index/index'));
    //         }
    //     }
    //     return view('login', [
            
    //     ]);
    // }

    public function login(){
        if (request()->isPost()) {
            $model = $this->model;
            $fields = [
                'must'=>['mobile','verify'],
                'nomust'=>['is_cookie']
            ];
            $param = paramFilter(request()->param(),$fields);
            if (!empty($param['error_msg'])) {
                $this->error($param['error_msg']);
            }

            $mobile = $param['mobile'];
            if (!isMobile($mobile)) {
                $this->error('手机号格式错误');    
            }
            if (empty($param['verify']) || $param['verify'] != session('sms_'.$mobile)) {
                $this->error('验证码错误');       
            }

            $map = [
                ['mobile','=',$mobile]
            ];
            $data = $model->where($map)->find();
            if ( empty($data) ) {
                $save_data = [
                    'mobile'=>$mobile,
                    'ctime'=>time(),
                    'nickname'=>'用户'.date('His')
                ];
                $save_data['headimgurl'] = Db::name('config')->where('key','USER_DEFAULT_IMG')->value('value');
                
                if ( Db::name('user')->insert($save_data) ) {
                    $data = Db::name('user')->where('mobile',$save_data['mobile'])->find();
                }else{
                    $this->error("注册失败");
                }
            }
            if ($data['status'] == 0) {
                $this->error("请等待业务人员开通授权");
            }

            session('sms_'.$mobile,null);
            session('cch_user',$data);
            if ($param['is_cookie'] == 'on') {
                cookie('cch_user_id',$data['id'],3600*24*7);
            }
            
            // $login_redirect_url = session('login_redirect_url');
            // if (request()->host() == 'video.deyunai.com') {
            //     $login_redirect_url = url('index/baidu_video/index');
            // }elseif (empty($login_redirect_url)) {
            //     $login_redirect_url = url('index/index');
            // }
            $login_redirect_url = url('index/index');

            return redirect($login_redirect_url);
        }

        // $view_path = request()->host() == 'video.deyunai.com' ? 'login_video' : 'login';
        $view_path = 'login';
        return view($view_path, [
            
        ]);
    }

    public function getCaptcha(){
        $captcha = new Captcha([        
            'codeSet'  => '1234567890', 
            'fontSize' => 18,
            'useCurve' => false,
            'imageH'   => 40,
            'length'   => 4,
            'reset'    => true
        ]);
        $data = $captcha->entry();
        return $data->getData();
    }

    

    public function register(){
        if (request()->isPost()) {
            $fields = [
                'must'=>['mobile','password'],
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                $this->error($save_data['error_msg']);
            }
            if (Db::name('user')->where('mobile',$save_data['mobile'])->count() > 0) {
                $this->error("手机已存在");
            }
            $save_data['password'] = md5($save_data['password']);
            $save_data['ctime'] = time();
            $save_data['nickname'] = '用户'.date('His');
            if ( Db::name('user')->insert($save_data) ) {
                $data = Db::name('user')->where('mobile',$save_data['mobile'])->find();
                session('cch_user',$data);
                return redirect(url('index/index'));
            }else{
                $this->error("注册失败");
            }
        }
        return view('register', [
            
        ]);
    }

    // public function login(){
    //     if (request()->isPost()) {
    //         $model = $this->model;
    //         $fields = [
    //             'must'=>['account','password','verify'],
    //             'nomust'=>['email']
    //         ];
    //         $param = paramFilter(request()->param(),$fields);
    //         if (!empty($param['error_msg'])) {
    //             $this->error($param['error_msg']);
    //         }

    //         if( !captcha_check($param['verify']) ){
    //             $this->error("验证码错误");
    //         }

    //         $map = [
    //             ['is_delete','=',0]
    //         ];
    //         if ( isMobile($param['account']) ) {
    //             $map[] = ['mobile','=',$param['account']];
    //         }else{
    //             $map[] = ['email','=',$param['account']];
    //         }
    //         if ( !empty($param['email']) ) {
    //             $map[] = ['email','=',$param['email']];   
    //         }
    //         $data = $model->where($map)->find();
    //         if ( empty($data) ) {
    //             $this->error("账号不存在");
    //         }elseif ( $data['password'] != md5($param['password']) ) {
    //             $this->error("账号或密码错误");
    //         }elseif ($data['status'] == 0){
    //             $this->error("账号未同步，请联系销售经理操作");
    //         }else{
    //             if ($data['mlogin_check'] == 1 && cookie('u_login_'.$data['mobile']) != 1) {
    //                 return redirect(url('mlogin',['mobile'=>$data['mobile'],'email'=>$data['email']]));
    //             }
    //             // 更新登录时间
    //             $model->where('id',$data['id'])->update(['login_time'=>time()]);

    //             session('cch_user',$data);
    //             return redirect(url('index/index'));
    //         }
    //     }
    //     return view('login', [
            
    //     ]);
    // }

    public function logout(){
        session('cch_user',null);
        cookie('cch_user_id',null);
        return redirect(url('login'));
    }

    public function view(){
        $model = $this->model;
        $id = $this->login_user['id'];
        $data = $model->where('id',$id)->find();
        $data['admin'] = Db::name('admin')->field('id,truename')->where('id',$data['admin_id'])->find();
        $data['total_recharge'] = Db::name('user_bill')->where([
            ['user_id','=',$id],
            ['type','=',1]
        ])->sum('amount');
        return view('view', [
            'data'=>$data
        ]);
    }

    public function update(){
        $ulogin = $this->login_user;
        $model = $this->model;
        if (request()->isPost()) {
            $fields = [
                'nomust'=>['nickname','truename','birthday','email','company','signature']
            ];
            $save_data = paramFilter(request()->param(),$fields);
            if (!empty($save_data['error_msg'])) {
                return json(['code'=>5000,'msg'=>$save_data['error_msg']]);
            }
            
            if (Db::name('user')->where('id',$ulogin['id'])->update($save_data) !== false) {
                return json(['code'=>2000]);
            }else{
                return json(['code'=>5000,'msg'=>'更新失败，请重试']);
            }
        }
    }

    // 修改密码
    public function changePwd(){
        $model = $this->model;
        if (request()->isPost()) {
            $fields = [
                'must'=>['old_pwd','new_pwd','confirm_pwd']
            ];
            $params = paramFilter(request()->param(),$fields);
            if (!empty($params['error_msg'])) {
                $this->error($params['error_msg']);
            }
            
            $id = $this->login_user['id'];
            $upwd = $model->where('id',$id)->value('password');
            if ($upwd != md5($params['old_pwd'])) {
                return json(['code'=>5000,'msg'=>'原登录密码错误']);
            }elseif ($params['new_pwd'] != $params['confirm_pwd']) {
                return json(['code'=>5000,'msg'=>'新密码与确认密码不一致']);
            }

            if ( $model->where('id',$id)->update([
                'password'=>md5($params['new_pwd'])
            ]) !== false ) {
                return json(['code'=>2000]);
            }else{
                return json(['code'=>5000,'msg'=>'更新失败']);
            }
        }
    }

   
   
}
